﻿using DataAccess.DTO;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
 
using System.Web.Security;

namespace Api
{
    /// <summary>
    /// 重写实现处理授权失败时返回json,避免跳转登录页
    /// </summary>
    public class ApiAuthorize : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var authorization = actionContext.Request.Headers.Authorization;
            if ((authorization != null) && (authorization.Parameter != null))
            {
                var encryptTicket = authorization.Parameter;
                if (EncodeSecurity.ValidateTicket(encryptTicket))
                {
                    base.IsAuthorized(actionContext);
                }
                else
                {
                    //HandleUnauthorizedRequest(actionContext);
                    actionContext.Response = ResultHand.OnResult(new Result { State = false, Message = "缺少Authorize信息" });
                }
            }
            else
            {
                //如果取不到身份验证信息，并且不允许匿名访问，则返回未验证401
                var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
                bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
                if (isAnonymous)
                { 
                    base.OnAuthorization(actionContext); 
                }
                else
                { 
                    //HandleUnauthorizedRequest(actionContext);
                    actionContext.Response = ResultHand.OnResult(new Result { State = false, Message = "缺少Authorize信息" });
                }
            }
        }
    }

    public class ActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            base.OnActionExecuting(actionContext);

            //获取请求消息提数据
            //Stream stream = actionContext.Request.Content.ReadAsStreamAsync().Result;
            //Encoding encoding = Encoding.UTF8;
            //stream.Position = 0;
            //string responseData = "";
            //using (StreamReader reader = new StreamReader(stream, encoding))
            //{
            //    responseData = reader.ReadToEnd().ToString();
            //}
            //var obj = JsonConvert.DeserializeObject<dynamic>(responseData);

            string encryptTicket = System.Web.HttpContext.Current.Request.Form["Authorization"];

            if (string.IsNullOrEmpty(encryptTicket))
            {
                actionContext.Response = ResultHand.OnResult(new Result { State = false, Message = "缺少Authorize信息" });
            }
            else
            {
                if (!EncodeSecurity.ValidateTicket(encryptTicket))
                {
                    actionContext.Response = ResultHand.OnResult(new Result { State = false, Message = "Authorize信息不正确" });
                }
            }
        }
    }

    public class EncodeSecurity
    {
        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string EncryptString(string text)
        {
            return XYD.Common.EncodeSecurity.EncryptString(text);
        }

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string DecryptString(string text)
        {
            return XYD.Common.EncodeSecurity.DecryptString(text);
        }

        //校验用户名密码
        public static bool ValidateTicket(string username, string password)
        {
            if (username == "admin" && password == "123123")
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static bool ValidateTicket(string encryptTicket)
        {
            //解密Ticket
            var strTicket = EncodeSecurity.DecryptString(encryptTicket);

            //从Ticket里面获取用户名和密码
            string[] up = strTicket.Split('&');
            if (up.Length < 2)
            {
                return false;
            }

            return ValidateTicket(up[0], up[1]);
        }

        //检验机器人登录加密数据
        public static bool ValidateRobotTicket(string encryptTicket)
        {
            //解密Ticket
            var strTicket = EncodeSecurity.DecryptString(encryptTicket);

            //从Ticket里面获取用户名和密码
            string[] up = strTicket.Split('&');
            if (up.Length == 3)
            {
                return true;
                //return ValidateRobotTicket(up[0], up[1]);
            }

            return false;
        }

        public static bool ValidateRobotTicket(string username, string password)
        {
            if (username == "account1" && password == "account1")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }

    public class RobotApiAuthorize : AuthorizeAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var authorization = actionContext.Request.Headers.Authorization;

            //authorization = actionContext.Request.Headers.GetValues("Authorization").FirstOrDefault();
            if ((authorization != null) && (authorization.Parameter != null))
            {
                var encryptTicket = authorization.Parameter;
                //xhr.setRequestHeader('Authorization', 'BasicAuth ' + getCookie("auth"));
                if (EncodeSecurity.ValidateRobotTicket(encryptTicket))
                {
                    base.IsAuthorized(actionContext);
                }
                else
                {
                    //HandleUnauthorizedRequest(actionContext);
                    actionContext.Response = ResultHand.OnResult(new Result { State = false, Message = "缺少Authorize信息" });
                }
            }
            else
            {
                //如果取不到身份验证信息，并且不允许匿名访问，则返回未验证401
                var attributes = actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().OfType<AllowAnonymousAttribute>();
                bool isAnonymous = attributes.Any(a => a is AllowAnonymousAttribute);
                if (isAnonymous)
                {
                    base.OnAuthorization(actionContext);
                }
                else
                {
                    //HandleUnauthorizedRequest(actionContext);
                    actionContext.Response = ResultHand.OnResult(new Result { State = false, Message = "缺少Authorize信息" });
                }
            }


 
        }
    }
}